﻿/*************************************************************************
 * Created by OhZee Creative, LLC
 * 2013
 * This code is licensed under Microsoft Public License (Ms-PL)
 * http://opensource.org/licenses/ms-pl
 * http://ozframework.codeplex.com/
 *************************************************************************/

namespace OhZeeCreative.Windows8.Converters
{
	using System;
	using System.Reflection;
	using Windows.UI;
	using Windows.UI.Xaml.Data;

    public sealed class ColorToNameConverter : IValueConverter
	{
		public bool ReturnFullName { get; set; }

		public object Convert(object value, Type targetType, object parameter, string language)
		{
			string name = null;

			if (value != null)
			{
				Color? nullableColor = value as Color?;

				if (value != null)
				{
					if (nullableColor.HasValue)
					{
						name = this.GetName(nullableColor.Value);
					}
				}
				else
				{
					name = this.GetName((Color) value);
				}
			}
			return name;
		}

		private string GetName(Color specifiedColor)
		{
			foreach (PropertyInfo info in typeof(Windows.UI.Colors).GetRuntimeProperties())
			{
				if (info.CanRead && info.PropertyType == typeof(Color) && info.PropertyType.GetTypeInfo().IsVisible)
				{
					Color color = (Color)info.GetValue(null);
					if (color == specifiedColor)
					{
						string text = info.Name;
						return ReturnFullName ? text : text.Substring(text.LastIndexOf(".") + 1);
					}
				}
			}
			return null;
		}

		public object ConvertBack(object value, Type targetType, object parameter, string language)
		{
			throw new NotImplementedException();
		}
	}
}
